from rest_framework import viewsets, permissions, status, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Ticket, TicketAssignment, TicketAction, TicketStatus
from .serializers import (
    TicketSerializer, TicketAssignmentSerializer, 
    TicketActionSerializer, TicketStatusSerializer
)
from django.contrib.auth.models import User


class TicketViewSet(viewsets.ModelViewSet):
    queryset = Ticket.objects.all()
    serializer_class = TicketSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['title', 'description', 'current_status']
    ordering_fields = ['created_at', 'updated_at']

    def perform_create(self, serializer):
        # 工单创建者默认为当前用户
        serializer.save(creator=self.request.user)

    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def assign(self, request, pk=None):
        ticket = self.get_object()
        handler_id = request.data.get('handler_id')

        if not handler_id:
            return Response(
                {'error': '处理人ID不能为空'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            handler = User.objects.get(id=handler_id)
        except User.DoesNotExist:
            return Response(
                {'error': '处理人不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )

        # 创建工单分配记录
        assignment = TicketAssignment.objects.create(
            ticket=ticket,
            handler=handler,
            status_at_assignment=ticket.current_status,
            notes=request.data.get('notes', '')
        )

        # 更新工单当前处理人
        ticket.current_handler = handler
        ticket.save()

        return Response(
            TicketAssignmentSerializer(assignment).data,
            status=status.HTTP_201_CREATED
        )

    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def update_status(self, request, pk=None):
        ticket = self.get_object()
        new_status = request.data.get('new_status')
        comment = request.data.get('comment', '')
        next_handler_id = request.data.get('next_handler_id')

        if not new_status:
            return Response(
                {'error': '新状态不能为空'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        if new_status not in dict(TicketStatus.choices):
            return Response(
                {'error': '无效的工单状态'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        # 检查权限：只有当前处理人或管理员可以更新工单状态
        user = request.user
        if ticket.current_handler != user and not user.is_staff:
            return Response(
                {'error': '只有当前处理人或管理员可以更新工单状态'}, 
                status=status.HTTP_403_FORBIDDEN
            )

        next_handler = None
        if next_handler_id:
            try:
                next_handler = User.objects.get(id=next_handler_id)
            except User.DoesNotExist:
                return Response(
                    {'error': '下一处理人不存在'}, 
                    status=status.HTTP_404_NOT_FOUND
                )

        # 创建工单操作记录
        action = TicketAction.objects.create(
            ticket=ticket,
            actor=user,
            from_status=ticket.current_status,
            to_status=new_status,
            comment=comment,
            next_handler=next_handler
        )

        # 更新工单状态和处理人
        ticket.current_status = new_status
        if next_handler:
            ticket.current_handler = next_handler
        elif new_status in [TicketStatus.CLOSED, TicketStatus.ASSISTANCE_COMPLETED]:
            ticket.current_handler = None

        ticket.save()

        return Response(
            TicketActionSerializer(action).data,
            status=status.HTTP_201_CREATED
        )


class TicketAssignmentViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = TicketAssignment.objects.all()
    serializer_class = TicketAssignmentSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['ticket__title', 'handler__username']
    ordering_fields = ['assigned_at']


class TicketActionViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = TicketAction.objects.all()
    serializer_class = TicketActionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['ticket__title', 'actor__username', 'from_status', 'to_status']
    ordering_fields = ['action_time']


class TicketStatusListView(viewsets.ViewSet):
    permission_classes = [permissions.IsAuthenticated]

    def list(self, request):
        statuses = [{'value': status[0], 'display_name': status[1]} for status in TicketStatus.choices]
        return Response(statuses)
